package org.ediba.siri.web;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.Properties;

import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.AbstractUrlBasedView;
import org.springframework.web.servlet.view.jasperreports.AbstractJasperReportsView;
import org.springframework.web.servlet.view.jasperreports.JasperReportsViewResolver;

public class MyJasperReportsViewResolver extends JasperReportsViewResolver {
	
	protected static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition";

	protected static final String CONTENT_DISPOSITION_ATTACHMENT = "attachment;filename=%1$s.pdf";
	
	private AbstractJasperReportsView imageView;
	public void setImageView(AbstractJasperReportsView view){this.imageView = view;}
	
	private AbstractJasperReportsView requestView;
	public void setRequestView(AbstractJasperReportsView view){this.requestView = view;}
	
	@Override
	public View resolveViewName(String viewName, Locale locale)	throws Exception {
		String _viewName;
		
		//caso especial, debo retornar la vista que envia inputstreams al report.
		if (viewName.endsWith("image/get"))
			_viewName = "image";
		else if (viewName.endsWith("request/get"))
			_viewName = "request";
		//casos grales
		else if (viewName.endsWith("model/get"))
			_viewName = "model";		
		//no hay reporte para lo que se solicita
		else 
			return null;
		
		return super.resolveViewName(_viewName, locale);
		
	}
	
	@Override
	protected AbstractUrlBasedView buildView(String viewName) throws Exception {

		AbstractJasperReportsView _view = null;
		String _filename = "";
		
		//caso especial, debo retornar la vista que envia inputstreams al report.
		if (viewName.equals("image")){
			_filename = "Imagenes_";
			_view = this.imageView;
		}
		else if (viewName.equals("request")){
			_filename = "Solicitudes_";
			_view = this.requestView;
		}
		//casos grales
		else {
			if (viewName.equals("model"))
				_filename = "Modelo_";
			_view = (AbstractJasperReportsView)super.buildView(viewName);
		}
	
		Properties _properties = new Properties();
		_properties.setProperty(HEADER_CONTENT_DISPOSITION, String.format(CONTENT_DISPOSITION_ATTACHMENT, _filename + new SimpleDateFormat("yyyy_MM_dd").format(Calendar.getInstance().getTime())));
		_view.setHeaders(_properties);
		return _view;
	}

}
